package cn.ydxiaoshuai.modules.controller;

import cn.ydxiaoshuai.common.api.vo.api.ImageAsciiResponse;
import cn.ydxiaoshuai.common.system.base.controller.ApiRestController;
import cn.ydxiaoshuai.modules.conts.LogTypeConts;
import cn.ydxiaoshuai.modules.util.ApiBeanUtil;
import cn.ydxiaoshuai.modules.weixin.po.WXAccessToken;
import com.alibaba.fastjson.JSON;
import com.baidu.aip.util.Base64Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


/**
 * 图片转字符图片
 *
 * @author 小帅丶
 * @date 2018年8月14日
 * <p>Description:图片转字符图片 </p>
 */
@Controller
@RequestMapping(value = "rest/ias")
@Scope("prototype")
@Slf4j
public class ImageAsciiRestController extends ApiRestController {
    @Autowired
    private ApiBeanUtil apiBeanUtil;

    /**
     * 图片转字符文本接口
     * @param file
     */
    @RequestMapping(value = "/image2ascii", method = {RequestMethod.POST})
    public ResponseEntity<Object> getImage2Ascii(@RequestParam(value = "file") MultipartFile file) {
        ImageAsciiResponse bean = new ImageAsciiResponse();
        WXAccessToken imgCheckBean = null;
        try {
            startTime = System.currentTimeMillis();
            param = "image="+ Base64Util.encode(file.getBytes())+",userId="+userId+",version="+version;
            if(LogTypeConts.API_VERSION.equals(version)){
                imgCheckBean = apiBeanUtil.checkImg(request, file);
                if(imgCheckBean.getErrcode()==0){
                    bean = apiBeanUtil.dealAsciiBean(file);
                }else{
                    bean.fail("img fail", imgCheckBean.getErrmsg(),imgCheckBean.getErrcode());
                }
            }else{
                bean = apiBeanUtil.dealAsciiBean(file);
            }
        } catch (Exception e) {
            errorMsg = e.getMessage();
            log.info("图片转字符文本接口出错了" + errorMsg);
            bean.error("system error", "系统错误");
        }
        //耗时
        timeConsuming = String.valueOf(System.currentTimeMillis() - startTime);
        log.info("图片背景色修改接口耗时{}",timeConsuming);
        beanStr = JSON.toJSONString(bean);
        apiBeanUtil.putLog(bean.getLog_id(), timeConsuming, beanStr, ip, param, requestURI, errorMsg, LogTypeConts.IMG_ASCII,userId,userAgent);
        //响应的内容
        return new ResponseEntity<Object>(JSON.toJSONString(bean), httpHeaders, HttpStatus.OK);
    }
}
